const PAGETITLE = "页面模板"

//生成前端文件

/**@description 生成搜索面板字段的模板函数 */
const createSearch = ({ searchConfig = Array, pageTitle = PAGETITLE }) => {
    return `
/**
 * ${pageTitle}页面的搜索字段配置
    * @param {Object} params - 配置参数对象
    * @param {Object} params.searchFormRef - 搜索表单的 ref 引用  searchFormRef?.current?.form 可获取整个表单，使用示例： searchFormRef?.current?.form.resetFields(); 会重置整个搜索表单
    * @returns {Array} 返回搜索字段配置数组，包含用户ID和用户名字段
    * object:
    *     name: 字段名，必填
    *     label: 字段标签，必填
    *     TYPE: 字段类型，必填，目前支持 Input、Select、RangePicker，Input 为输入框，Select 为下拉框，RangePicker 为日期范围选择器，parseFields 为解析字段，用于解析日期范围选择器返回的日期字符串，示例：parseFields: ['startDateTime', "endDateTime"]，startDateTime 为开始日期字段名，endDateTime 为结束日期字段名
    *
    * @example
    * const searchFields = getSearchFields({ searchFormRef: formRef });
    */
const getSearchFields = ({ searchFormRef = null }) => {
    return [ ${searchConfig.map(item => {
        return `
        {
            name: '${item.name}',
            label: '${item.label}',
           TYPE: '${item.TYPE}'
        }`
    })}
    ]
        }
        export default getSearchFields;

        `
}

/**@description 生成columns模板 */
const createColumns = ({ columnsConfig = Array, pageTitle = PAGETITLE }) => {
    return `

/**
 * ${pageTitle}的表格列配置
 * @param {Object} params - 配置参数对象
 * @param {Function} params.open - 打开编辑弹窗的回调函数
 * @param {Function} params.handleDelete - 处理删除操作的回调函数
 * @returns {Array} 返回表格列配置数组，包含访客IP、地区、访问时间、访问页面、渠道来源等字段
 * object:
 *     title: 列标题，必填
 *     dataIndex: 列数据在数据项中对应的 key，必填
 *     width: 列宽度，选填，不填默认为 100
 *     type: 列类型，选填，不填默认为 Text，可选值：Date， 为日期，日期格式默认为 YYYY-MM-DD HH:mm:ss
 *     format: 日期格式，选填，不填默认为 YYYY-MM-DD HH:mm:ss，
 */
const getColumns = ({ open = Function, handleDelete = Function }) => {
    return [
        ${columnsConfig.map(item => {
            return `
            {
                title: "${item.title}",
                key: "${item.dataIndex}",
                dataIndex: "${item.dataIndex}",
                width: 180,
            },`
        })}
        // {
        //     title: "操作",
        //     key: "action",
        //     dataIndex: "action",
        //     width: 280,
        //     render: (text, record) => {
        //         return <Space>
        //             <Button type="link" onClick={() => open({ type: "update", record: record })}>编辑</Button>
        //             <Button type="link" danger onClick={() => handleDelete(record)}>删除</Button>
        //         </Space>
        //     }
        // }
    ];
}

export default getColumns;`

}

/**@description 生成功能区 */
const createAction = ({ pageTitle = PAGETITLE }) => {

    return `
import React from "react";
import { Button } from "antd";
import { PlusOutlined,  DownloadOutlined } from '@ant-design/icons';


/**
 * @description ${pageTitle}功能区 例如：新建 导出 等功能
 * @param {config} config 配置可以传入一些需要的其他参数或者元素 注意，此参数是一个Object 对象 
 * */
const getActoinPanel = (config = Object) => {
    const { editForm = Function } = config;
    const actionConfig = [
        // {
        //     show: true,
        //     render: (newSelectRows = [], key) => <Button key={key}
        //         onClick={() => {
        //             // let object = { ...params, ...getSerachFormData() }
        //             console.log("当前的导出条件：", object);
        //         }}
        //         type="primary" icon={<DownloadOutlined />} >导出</Button>
        // },
        {
            show: true,
            icon: <PlusOutlined />,
            type: "",
            text: "新增",
            onClick: () => editForm({ type: "add", record: {} })
        },
    ];
    return actionConfig;
}
export default getActoinPanel;
    `
}


/**@description 生成页面主代码 */
const createIndex = ({ pageTitle = PAGETITLE, componentName }) => {
    return (
        `
import { initSearchConfig, TableSearchPanel, XxpageContainer, XxTable } from "@/ui";
import React, { useEffect, useRef, useState } from "react";
import {getSearchFields,getActoinPanel,getColumns} from "./config";
import EditForm from "./editForm";
import { testApi as api } from "@/api";
import { globalModal } from "@/data";

/**@description 【${pageTitle}】页面 */
const ${componentName} = () => {
    const searchFormRef = useRef(null); //搜索表单的引用对象，用于获取/操作表单实例
    const editFormRef = useRef(null); //用于引用编辑表单的 ref 对象
    const [params, setParams] = useState({ ...initSearchConfig(getSearchFields({searchFormRef})) })
    const [state, setState] = useState({
        data: [],
        totalCount: 0
    })
    const [loading, setLoading] = useState(false);

    //搜索事件
    const onClickSearch = (value) => {
        setParams({
            ...params,
            ...value,
            current: 1,
        });
    };


    /**@description 查找列表 */
    const getList = async () => {
        setLoading(true);
        const { data, code, msg } = await api.queryList({ pageSize: 10, current: 1, ...params });
        setState({
            data: [...data.list],
            totalCount: data.totalCount || 0,
        })
        setLoading(false);

    }

    const onChange = (current, pageSize) => {
        setParams({
            ...params,
            current,
            pageSize
        })
    }
    useEffect(() => {
        getList()
    }, [params])

    /**  @description 打开编辑菜单窗口 */
    const open = ({ type = "add", record = Object }) => {
        editFormRef.current.open({ type, record });
    }

    /**@description 删除按钮操作 */
    const handleDelete = async (object) => {
        globalModal.methods.modal.confirm({
            title: "确认删除吗",
            centered: true,
            content: "删除后数据不可恢复",
            onOk: async () => {
                const { code, msg } = await api.delete(object.id)
                globalModal.methods.modal.success({
                    centered: true,
                    title: "提示",
                    content: msg
                })
                getList()
            }
        })
    }


    const [selectedKeys, setSelectedKeys] = useState([])
    const onSelectChange = (newSelectedRowKeys, selectedRows) => {
        setSelectedKeys(newSelectedRowKeys);
    }
    const actionPanel = getActoinPanel({
        open: open,

    })
    const tableProps = {
        hideActionPanel: false,
        tablePanelConfig: actionPanel,
        loading,
        columns: getColumns({ open, handleDelete }),
        dataSource: state.data,
        pagination: {
            total: state.totalCount,
            pageSize: params.pageSize,
            onChange: onChange,
            current: params.current

        },
        rowSelection: {
            type: "checkbox",
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
        },
        rowKey: 'id',
        selectRecords: selectedRows,
        selectedRowKeys: selectedKeys,
        onRow: (record, index) => {
            return {
                onDoubleClick: () => {

                }
            }
        },
    }


    return (
        <XxpageContainer>
            <EditForm onRef={editFormRef} getList={getList} />
            <TableSearchPanel
                onRef={searchFormRef}
                fields={getSearchFields({ searchFormRef })}
                onSearch={onClickSearch}
            />
            <XxTable  {...tableProps} />

        </XxpageContainer>
    )
}

export default ${componentName};
    `
    )
}

/**@description 生成API文件 */
const createApi = ({ componentName }) => {
    return `
import request from "@/service/axios/index";

/**@description 【${componentName}】页面接口API */
const ${componentName}Api = {
    /**@description 查询列表 */
    queryList: (data) => {
        return request.post({ url: '/dev/codeGengeration/list', data })
    },
    /**@description 删除 */
    delete: (id) => {
        return request.delete({ url: '/dev/codeGengeration/delete?id=' + id })
    },
    /**@description 保存数据 */
    saveData: (data) => {
        return request.post({ url: "/dev/codeGengeration/save", data })
        },
        /**@description 获取详情 */
        getDetail: (id) => {
            return request.get({ url: "/dev/codeGengeration/detail?id=" + id })
        }
}
export default ${componentName}Api;
`

}
/**@description 生成配置Index文件 */
const createConfigIndex = ({ pageTitle, componentName }) => {
    return `
export { default as getActoinPanel } from './actionPanel';
export { default as getColumns } from './columns';
export { default as getSearchFields } from './searchPanel';
`

}

/**@description 生成editForm表单组件 */
const createEditForm = ({ componentName }) => {
    return `

import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { Col, Form, Input, Modal, Row, Select, InputNumber, Flex, Radio, Spin, TreeSelect, message } from "antd";
import React, { useState, useEffect, useRef, useImperativeHandle, } from "react";
import { userApi } from "@/api";

const ${componentName} = ({ onRef, getList = Function }) => {
    const [show, setShow] = useState(false);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();



    /**@description 表单布局 */
    const formItemLayout = {
        labelCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 4,
            },
        },
        wrapperCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 20,
            },
        },
    };

    /**@description 取消 */
    const onCanle = () => {
        setShow(false);
    }

    /**@description 添加|修改操作 */
    const open = async ({ type = String || undefined, record = Object }) => {
        const { id = undefined } = record;
        setShow(true);
        form.resetFields();
        form.setFieldValue("type", "action." + type)

        if (type === "update") {

            if (id) {
                try {
                    setLoading(true);
                    const data = await userApi.getUser(id);
                    console.log("编辑，详情", data)
                    form.setFieldsValue({
                        type: type || undefined,
                        ...data
                    });


                } catch (error) {

                } finally {
                    setLoading(false);
                }
            }
        } else if (type === "add") {
            // // 新增 
            form.setFieldsValue({
                passWord: "123456"
            })
        } else {
        }



    }

    /**@description 异步保存数据 */
    const createMenu = async (value) => {

        try {
            const data = await userApi.createUser(value);
            getList();
            onCanle();
        } catch (error) {

        } finally {

        }

    }

    /**@description 校验表单 */
    const validateForm = async () => {
        form.validateFields().then(res => {
            console.log("校验参数：", res)
            createMenu(res)
        })
    }

    /**@description 向外暴露方法 */
    useImperativeHandle(onRef, () => ({
        open
    }))

    /**@description form表单props配置 */
    const formProps = {
        form,
        initData: {
            type: undefined,
            parentId: "0",
            menuType: "1"
        }
    }

    useEffect(() => {
        !show && form.resetFields()
    }, [show])



    return (
        <>
            <Modal
                title="编辑员工"
                width={550}
                open={show}
                centered={true}
                destroyOnClose={true}
                onCancel={onCanle}
                onOk={validateForm}
            >
                <Spin spinning={loading}>
                    <Form
                        {...formItemLayout}
                        {...formProps}
                    >
                        <Row gutter={24}>
                            <Col span={24} style={{ display: "none" }} >
                                <Form.Item label="id" name="id">
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="用户ID" name="userId">
                                    <Input placeholder="请输入用户ID" />
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item label="用户姓名" name="userName" >
                                    <Input placeholder="请输入用户姓名" />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="初始密码" name="passWord" help="新增的用户默认密码为123456">
                                    <Input.Password disabled placeholder="请输入用户密码" />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Spin>

            </Modal>
        </>
    )
}
export default ${componentName};
`
}


//生成后端 nodejs 模型文件
const createNodejsModel = ({ pageTitle, componentName, tableName, modelData = [] }) => {
    const disparseType = type => {
        switch (type) {
            case "number":
                return "Number"
            case "string":
                return "String"
            case "datetime":
                return "Date"
            case "text":
                return "String"
            default:
                return "String"
        }
    }


    const disparseIndexStr = () => {

        let str = "";
        modelData.forEach(item => {
            if (item.index) {
                str += `Schema.index({ ${item.filed}: 1 });\n`
            }
        })
        return str;
    }





    return `
const mongoose = require("../../../db/db");

/**
 * @description ${pageTitle}模型
 */
const Schema = mongoose.Schema({
    ${modelData.map(item => (`
    // ${item.desc}
    ${item.filed}: {
        type: ${disparseType(item.type)},
        require: ${item.require},
        unique: ${item.unique},
    }\n`))
        }
}, {
    versionKey: false, // 去除版本号
    // 自动创建 createdAt 和 updatedAt 时间戳（可选）
    timestamps: { createdAt: "createDate", updatedAt: "updateDate" }
})


// --------------------------
// 索引配置
// --------------------------
// 单字段索引示例
// Schema.index({ createDate: -1 });
// Schema.index({ sort: 1 });
${disparseIndexStr()}

// // 复合索引示例
// Schema.index({ status: 1, deleteFlag: 1, createDate: -1 });
// Schema.index({ status: 1, sort: 1 });
// 
// // 唯一索引示例
// Schema.index({ id: 1 }, { unique: true });
// 
// // 文本索引（全文搜索）示例
// Schema.index(
//     { title: "text", intro: "text", description: "text" },
//     {
//         weights: { title: 10, intro: 5, description: 3 },
//         name: "article_text_search"
//     }
// );

// --------------------------
// 导出模型
// --------------------------
/**@description ${pageTitle}表模型 */
const ${tableName}_model = mongoose.model("${tableName}", Schema);
module.exports = ${tableName}_model;
    `
}



module.exports = {
    createConfigIndex, createEditForm, createNodejsModel,
    createSearch, createColumns, createAction, createIndex, createApi
}